import {createStore} from "vuex"
import createPersistedState from "vuex-persistedstate"

// 实例化一个vue存储库
const store = createStore({
    // 调用永久存储vuex数据的插件，localstorage里会多一个名叫vuex的Key，里面就是vuex的数据
    plugins: [createPersistedState()],
    state() {// 数据存储位置
        return {
            user: {}
        }
    },
    getters: {
        getUserInfo(state) {
            // 从jwt的载荷中提取用户信息
            let now = parseInt((new Date() - 0) / 1000);
            if (state.user.exp === undefined) {
                // 没登录
                state.user = {}
                localStorage.access_token = null;
                localStorage.refresh_token = null;
                sessionStorage.access_token = null;
                sessionStorage.refresh_token = null;
                return null
            }

            if (parseInt(state.user.exp) < now) {
                // 过期处理
                state.user = {}
                localStorage.access_token = null;
                localStorage.refresh_token = null;
                sessionStorage.access_token = null;
                sessionStorage.refresh_token = null;
                return null
            }
            return state.user;
        }
    },
    mutations: {// 操作数据的方法
        login(state, user) {// 传入一个参数user
            state.user = user
        },
        logout(statue) {
            statue.user = {};
            localStorage.access_token = null;
            localStorage.refresh_token = null;
            sessionStorage.access_token = null;
            sessionStorage.refresh_token = null;
        }
    }
})

export default store;